# -*- coding: utf-8 -*-

import FPLib,json,os,re

log=FPLib.log("config")

class config:

    def __init__(self,config_file="config.conf"):
        self.__config_file="config.conf"
        self.config={}
        self.ctime=""
        self.load(config_file)

    def load(self,config_file):
        self.__config_file=FPLib.FILE(config_file)
        self.reload()

    def reload(self):
        self.ctime=os.path.getctime(self.__config_file)
        try:
            with open(self.__config_file,'r') as f1:
                self.config = self.parse_json(f1.read())
        except Exception as e:
            log.error(e)


    def get(self,key,default=""):

        if self.ctime!=os.path.getctime(self.__config_file):
            self.reload()

        conf=self.config
        try:
            for item in key.split('.'):
                conf=conf.get(item,default)
        except:
            conf=default
        return conf
    def __getattr__(self, name):
        return self.get(name,"")

    def parse_json(self,str,**kwargs):
        text=str.strip()
        regex = r'\s*(#|\/{2}).*$'
        regex_inline = r'(:?(?:\s)*([A-Za-z\d\.{}]*)|((?<=\").*\"),?)(?:\s)*(((#|(\/{2})).*)|)$'
        lines = text.split('\n')

        for index, line in enumerate(lines):
            if re.search(regex, line):
                if re.search(r'^' + regex, line, re.IGNORECASE):
                    lines[index] = ""
                elif re.search(regex_inline, line):
                    lines[index] = re.sub(regex_inline, r'\1', line)

        try:
            return json.loads('\n'.join(lines), **kwargs)
        except Exception as e:
            log.error(e)
            return None
